//
//  MusicDetailViewController.m
//  B
//
//  Created by 王展 on 15/11/12.
//  Copyright © 2015年 wangzhan. All rights reserved.
//

#import "MusicDetailViewController.h"
#import "MusicDetail.h"

#import <STKAudioPlayer.h>

#import <AVFoundation/AVFoundation.h>

#import <MediaPlayer/MediaPlayer.h>

@interface MusicDetailViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,STKAudioPlayerDelegate,NSURLSessionDownloadDelegate>

@property(nonatomic,retain)STKAudioPlayer *player;

@property(nonatomic,retain)UICollectionViewFlowLayout *flowLayout;
@property(nonatomic,retain)UICollectionView *musicCV;
@property(nonatomic,retain)MusicDetail *amusicDetail;
@property(nonatomic,retain)Music *music;
@property(nonatomic,copy)NSString *nowSource;

@property(nonatomic,retain)NSTimer *timer;


@property(nonatomic,retain)UIImage *startImage;
@property(nonatomic,retain)UIImage *endImage;
@property(nonatomic,retain)UILabel *name;
@property(nonatomic,retain)UILabel *info;
@property(nonatomic,retain)UIImageView *imageView;
@property(nonatomic,retain)UISlider *musicSlider;
@property(nonatomic,retain)UILabel *timeLabel;
@property(nonatomic,retain)UIButton *nextButton;
@property(nonatomic,retain)UIButton *lastButton;
@property(nonatomic,retain)UIButton *startButton;
@property(nonatomic,retain)UIView *tempView1;
@property(nonatomic,retain)UIView *tempView2;
@property(nonatomic,retain)UIView *tempView3;
@property(nonatomic,retain)UIImage *amusicImage;

@property(nonatomic,strong)UIButton *xunhuanButton;
@property(nonatomic,strong)UIButton *xiazaiButton;
@property(nonatomic,strong)UIButton *shoucangButton;

@property(nonatomic,strong)UIImage *xunhuan;
@property(nonatomic,strong)UIImage *danquxun;
@property(nonatomic,strong)UIImage *suiji;
@property(nonatomic,strong)UIImage *xiazai;
@property(nonatomic,strong)UIImage *yishoucang;
@property(nonatomic,strong)UIImage *shoucang;




//下载用的属性
@property(nonatomic,strong)NSURLSessionDownloadTask *downLoadTask;
@property(nonatomic,strong)UILabel *currentProgress;

@end

@implementation MusicDetailViewController

+(instancetype)sharePlayerViewController
{
    static MusicDetailViewController *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[MusicDetailViewController alloc] init];
    });
    return player;
}


//更新锁屏时的歌曲信息
-(void)newMusicInfo
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    
    [dict setObject:[MusicDetailViewController sharePlayerViewController].amusic.name forKey:MPMediaItemPropertyTitle];
    
    [dict setObject:@"FN" forKey:MPMediaItemPropertyArtist];
    
    [dict setObject:@"推荐" forKey:MPMediaItemPropertyAlbumTitle];
    
    if ([MusicDetailViewController sharePlayerViewController].amusicImage != nil) {
        MPMediaItemArtwork *albumArt = [ [MPMediaItemArtwork alloc] initWithImage:[MusicDetailViewController sharePlayerViewController].amusicImage];
        
        [dict setObject:albumArt forKey:MPMediaItemPropertyArtwork];
    }
    
    [dict setObject:[NSNumber numberWithDouble:self.player.progress] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime]; //音乐当前已经播放时间
    [dict setObject:[NSNumber numberWithDouble: self.player.duration] forKey:MPMediaItemPropertyPlaybackDuration];//总过时间
    
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    //后台播放
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    //申请后台,锁屏播放按钮功能
    [[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
    
    //监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outputDeviceChanged:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
    
    
    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    self.player.volume = 0.5;
    self.player.delegate = self;
    [self.player play:self.amusic.source];
    
    [self createDetailMuscicSubView];
    [self createMusicDetailView];
}

-(void)createMusicDetailView
{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.itemSize = CGSizeMake(WIDTH - 20, WIDTH + 30 * XHIGHT);
    self.flowLayout.minimumLineSpacing = 10 * XHIGHT;
    self.musicCV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT - 64) collectionViewLayout:self.flowLayout];
    self.musicCV.delegate = self;
    self.musicCV.dataSource = self;
    self.musicCV.bounces = NO;
    self.musicCV.backgroundColor = [UIColor colorWithRed:251/255.0 green:247 /255.0 blue:236/255.0 alpha:1];
    [self.view addSubview:self.musicCV];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 2;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.musicCV registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    if (indexPath.row == 0) {
        
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.amusic.pic] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            self.amusicImage = image;
            [self newMusicInfo];
        }];
        
        [cell.contentView addSubview:self.imageView];
        [cell.contentView addSubview:self.nextButton];
        [cell.contentView addSubview:self.lastButton];
        [cell.contentView addSubview:self.startButton];
        
        [cell.contentView addSubview:self.xunhuanButton];
        [cell.contentView addSubview:self.xiazaiButton];
        [cell.contentView addSubview:self.shoucangButton];
        
        [cell.contentView addSubview:self.tempView1];
        [cell.contentView addSubview:self.tempView2];
        [cell.contentView addSubview:self.tempView3];
        
        
        [cell.contentView addSubview:self.currentProgress];
    }
    else
    {
        self.name.text = self.amusicDetail.name;
        self.name.font = [UIFont systemFontOfSize:17 * XWIDTH];
        self.name.textColor = [UIColor colorWithRed:50 / 255.0 green:50 / 255.0 blue:50 / 255.0 alpha:1.0];
        self.name.numberOfLines = 0;
        self.name.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:self.name];
        
        self.info.numberOfLines = 0;
        self.info.font = [UIFont systemFontOfSize:16 * XWIDTH];
        self.info.textColor = [UIColor grayColor];
        [cell.contentView addSubview:self.info];
    }
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return CGSizeMake(WIDTH, WIDTH + 100 * XHIGHT);
    }
    else
    {
        self.info.text = self.amusicDetail.info;
        self.info.frame = CGRectMake(10 * XWIDTH, 50 * XHIGHT, WIDTH - 20 * XWIDTH, 0);
        [self.info sizeToFit];
        return CGSizeMake(WIDTH, self.info.frame.size.height + 90 * XHIGHT);
    }
}

-(void)createDetailMuscicSubView
{
    self.suiji = [UIImage imageNamed:@"suiji.png"];
    self.xunhuan = [UIImage imageNamed:@"xunhuan.png"];
    self.danquxun = [UIImage imageNamed:@"danquxun.png"];
    self.xiazai = [UIImage imageNamed:@"xiazai.png"];
    self.shoucang = [UIImage imageNamed:@"shoucang.png"];
    self.yishoucang = [UIImage imageNamed:@"yishoucang.png"];
    
    self.startImage = [UIImage imageNamed:@"iconfont-bofangqibofang.png"];
    self.endImage = [UIImage imageNamed:@"iconfont-zanting-2.png"];
    UIImage *lastImage = [UIImage imageNamed:@"iconfont-bofangqishangyiqu.png"];
    UIImage *nextImage = [UIImage imageNamed:@"iconfont-bofangqixiayiqu.png"];
    self.name = [[UILabel alloc] initWithFrame:CGRectMake(10 * XWIDTH, 10 * XWIDTH,  WIDTH - 20 * XWIDTH, 30 * XHIGHT)];
    self.info = [[UILabel alloc] initWithFrame:CGRectMake(10 * XWIDTH, 80 * XHIGHT, WIDTH - 20 * XWIDTH, 0)];
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, WIDTH)];
    self.imageView.userInteractionEnabled = YES;
    self.musicSlider = [[UISlider alloc] initWithFrame:CGRectMake(-5 * XWIDTH, WIDTH - 30 * XHIGHT, WIDTH + 10 * XWIDTH, 30 * XHIGHT)];
    UIImage *sliderImage = [UIImage imageNamed:@"music.png"];
    UIImage *newSliderImage = [self scaleToSize:sliderImage size:CGSizeMake(WIDTH + 10 * XWIDTH, 30 * XHIGHT)];
    [self.musicSlider setMaximumTrackImage:newSliderImage forState:0];
    UIImage *sliderImage2 = [UIImage imageNamed:@"musicTiao.png"];
    UIImage *newsliderImage2 = [self scaleToSize:sliderImage2 size:CGSizeMake(WIDTH + 10 * XWIDTH, 30 * XHIGHT)];
    [self.musicSlider setMinimumTrackImage:newsliderImage2 forState:0];
    UIImage *kuaiImage = [UIImage imageNamed:@"kuai.png"];
    UIImage *newKuaiImage = [self scaleToSize:kuaiImage size:CGSizeMake(10 * XWIDTH, 30 * XHIGHT)];
    [self.musicSlider setThumbImage:newKuaiImage forState:0];
    [self.imageView addSubview:self.musicSlider];
    [self.musicSlider addTarget:self action:@selector(musicSliderAction:) forControlEvents:UIControlEventValueChanged];
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10 * XWIDTH, WIDTH - 30 * XHIGHT, 150 * XWIDTH, 30 * XHIGHT)];
    self.timeLabel.font = [UIFont systemFontOfSize:15 * XHIGHT];
    self.timeLabel.textColor = [UIColor whiteColor];
    [self.imageView addSubview:self.timeLabel];
    [self.imageView bringSubviewToFront:self.timeLabel];
    self.startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.startButton setImage:self.endImage forState:0];
    self.startButton.titleLabel.textColor = [UIColor grayColor];
    [self.startButton addTarget:self action:@selector(startButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.startButton.frame = CGRectMake(200, WIDTH, 30 * XWIDTH, 30 * XWIDTH);
    self.startButton.center = CGPointMake(WIDTH / 2, WIDTH + 25 * XWIDTH);
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextButton.frame = CGRectMake(300 * XWIDTH, WIDTH + 12 * XWIDTH, 25 * XWIDTH , 25 * XWIDTH);
    [self.nextButton setImage:nextImage forState:0];
    [self.nextButton addTarget:self action:@selector(nextButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.lastButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.lastButton.frame = CGRectMake(50 * XWIDTH, WIDTH + 12 * XWIDTH, 25 * XWIDTH, 25 * XWIDTH);
    [self.lastButton setImage:lastImage forState:0];
    [self.lastButton addTarget:self action:@selector(lastButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.tempView1 = [[UIView alloc] initWithFrame:CGRectMake(120 * XWIDTH, WIDTH, 1, 100 * XHIGHT)];
    self.tempView1.backgroundColor = [UIColor lightGrayColor];
    
    self.tempView2 = [[UIView alloc] initWithFrame:CGRectMake(250 * XWIDTH, WIDTH, 1, 100 * XHIGHT)];
    self.tempView2.backgroundColor = [UIColor lightGrayColor];
    self.tempView3 = [[UIView alloc] initWithFrame:CGRectMake(0, WIDTH + 50 * XHIGHT - 1, WIDTH, 1)];
    self.tempView3.backgroundColor = [UIColor lightGrayColor];
    
    self.xunhuanButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.xunhuanButton.frame = CGRectMake(50 * XWIDTH, WIDTH + 62 * XWIDTH, 25 * XWIDTH, 25 * XWIDTH);
    //    self.xunhuanButton.backgroundColor = [UIColor redColor];
    [self.xunhuanButton setImage:self.xunhuan forState:0];
    [self.xunhuanButton addTarget:self action:@selector(xunhuanButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.xunhuanButton.tag = 4001;
    
    self.xiazaiButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.xiazaiButton.frame = CGRectMake(0, 0, 25 * XWIDTH, 25 * XWIDTH);
    self.xiazaiButton.center = CGPointMake(WIDTH / 2, WIDTH + 65 * XWIDTH);
    //    self.xiazaiButton.backgroundColor = [UIColor redColor];
    [self.xiazaiButton setImage:self.xiazai forState:0];
    [self.xiazaiButton addTarget:self action:@selector(xiazaiButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.currentProgress = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 70 * XWIDTH, 25 * XWIDTH)];
    self.currentProgress.center = CGPointMake(WIDTH / 2, WIDTH + 85 * XWIDTH);
    self.currentProgress.font = [UIFont systemFontOfSize:15 * XWIDTH];
    
    
    
    
    self.shoucangButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.shoucangButton.frame = CGRectMake(300 * XWIDTH, WIDTH + 62 * XWIDTH, 25 * XWIDTH, 25 * XWIDTH);
    //    self.shoucangButton.backgroundColor = [UIColor redColor];
    [self.shoucangButton setImage:self.shoucang forState:0];
    [self.shoucangButton addTarget:self action:@selector(shoucangButtonAction) forControlEvents:UIControlEventTouchUpInside];
}


//改变图片大小
-(UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size
{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

//获取详情数据
-(void)getMusicDetailData
{
    NSString *url_str = [NSString stringWithFormat:@"http://echosystem.kibey.com/sound/info?sound_id=%@",self.amusic.id];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setValue:@"PHPSESSID=qtur65hr4cg4d60amesrt5ndm6" forHTTPHeaderField:@"Cookie"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *bigDic = responseObject;
        NSMutableDictionary *dic = [bigDic objectForKey:@"result"];
        self.amusicDetail = [[MusicDetail alloc] init];
        [self.amusicDetail setValuesForKeysWithDictionary:dic];
        [self.musicCV reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"没有网络");
    }];
}


//传一个音乐对象
-(void)setAmusic:(Music *)amusic
{
    _amusic = amusic;
    
    if (self.nowSource != self.amusic.source) {
        [self.player play:self.amusic.source];
        self.nowSource = self.amusic.source;
        [self.startButton setImage:self.endImage forState:0];
        
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.amusic.pic] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            self.amusicImage = image;
            [self newMusicInfo];
        }];
    }
    
    [self getMusicDetailData];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
}

-(void)startButtonAction
{
    if (self.player.state == STKAudioPlayerStatePaused) {
        
        NSLog(@"暂停");
        [self.startButton setImage:self.endImage forState:0];
        [self.player resume];
        
    }else if (self.player.state == STKAudioPlayerStatePlaying) {
        
        NSLog(@"播放");
        [self.startButton setImage:self.startImage forState:0];
        [self.player pause];
        
    }else
    {
        [self getMusicDetailData];
    }
    
}

-(void)nextButtonAction
{
    if (self.xunhuanButton.tag == 4001) {
        self.indexRow++;
        if (self.indexRow == self.allMusicArray.count) {
            self.indexRow = 0;
        }
        self.amusic = [self.allMusicArray objectAtIndex:self.indexRow];
    }else if (self.xunhuanButton.tag == 4002){
        self.amusic = [self.allMusicArray objectAtIndex:self.indexRow];
        [self.startButton setImage:self.endImage forState:0];
        [self.player play:self.amusic.source];
    }else if (self.xunhuanButton.tag == 4003){
        
        self.indexRow = (arc4random() % self.allMusicArray.count);
        self.amusic = [self.allMusicArray objectAtIndex:self.indexRow];
        [self.startButton setImage:self.endImage forState:0];
        [self.player play:self.amusic.source];
    }
}

-(void)lastButtonAction
{
    if (self.xunhuanButton.tag == 4001) {
        self.indexRow--;
        if (self.indexRow == -1) {
            self.indexRow = self.allMusicArray.count - 1;
        }
        self.amusic = [self.allMusicArray objectAtIndex:self.indexRow];
    }else if (self.xunhuanButton.tag == 4002){
        self.amusic = [self.allMusicArray objectAtIndex:self.indexRow];
        [self.startButton setImage:self.endImage forState:0];
        [self.player play:self.amusic.source];
    }else if (self.xunhuanButton.tag == 4003){
        self.indexRow = (arc4random() % self.allMusicArray.count);
        self.amusic = [self.allMusicArray objectAtIndex:self.indexRow];
        [self.startButton setImage:self.endImage forState:0];
        [self.player play:self.amusic.source];
    }
}

//每隔一秒调用该方法
-(void)track
{
    self.musicSlider.maximumValue = self.player.duration;//音乐总时长
    self.musicSlider.value = self.player.progress;//当前进度
    
    //当前时长进度progress
    NSInteger proMin = (NSInteger)self.player.progress / 60;//当前秒
    NSInteger proSec = (NSInteger)self.player.progress % 60;//当前分钟
    
    //duration 总时长
    NSInteger durMin = (NSInteger)self.player.duration / 60;//总秒
    NSInteger durSec = (NSInteger)self.player.duration % 60;//总分钟
    
    self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", proMin, proSec, durMin, durSec];
}

-(void)musicSliderAction:(UISlider *)sender
{
    if (self.player) {
        [self.player seekToTime:sender.value];
    }
}


-(void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId
{
    NSLog(@"开始播放");
}
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId
{
    NSLog(@"完成加载");
}
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    NSLog(@"播放状态改变");
}
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    NSLog(@"结束播放");
    NSLog(   @"stopReason:  %d"    @"progress:  %f"  @"duration: %f",stopReason,progress,duration);
    if (stopReason == 1) {
        [self nextButtonAction];
    }
}

-(void)xunhuanButtonAction:(UIButton *)button
{
    NSLog(@"循环");
    if (button.tag == 4001) {
        [self.xunhuanButton setImage:self.danquxun forState:0];
        self.xunhuanButton.tag = 4002;
    }else if (button.tag == 4002)
    {
        [self.xunhuanButton setImage:self.suiji forState:0];
        self.xunhuanButton.tag = 4003;
    }else if (button.tag == 4003)
    {
        [self.xunhuanButton setImage:self.xunhuan forState:0];
        self.xunhuanButton.tag = 4001;
    }
}


-(void)shoucangButtonAction
{
    NSLog(@"收藏");
}

-(void)xiazaiButtonAction
{
    NSLog(@"下载");
    
    NSLog(@"source == %@",self.amusic.source);
    
    self.currentProgress.hidden = NO;
    
    NSURL *url = [NSURL URLWithString:self.amusic.source];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //NSURLSessionDownloadDelegate 签订协议
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //创建下载任务对象
    self.downLoadTask = [session downloadTaskWithRequest:request];
    //开始执行下载任务
    [self.downLoadTask resume];
    
    //暂停下载
    //    [self.downLoadTask suspend];
}

//下载完成后调用
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSLog(@"path===%@",location.path);//系统缓存路径
    
    NSLog(@"suggestedFilename===%@",downloadTask.response.suggestedFilename);//系统自动生成的文件名
    
    // response.suggestedFilename 系统建议使用的文件名，也可以自定义文件名
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *file = [caches stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",downloadTask.response.suggestedFilename]];
    
    //保存图片
    //NSString *file = [caches stringByAppendingPathComponent:@"yutao.png"];
    
    
    NSLog(@"file =======%@",file);
    
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    [mgr moveItemAtPath:location.path toPath:file error:nil];
    
    self.currentProgress.hidden = YES;
    
}

/**
 *  该方法会执行多次,每次都会下载不同大小的数据
 *
 *  @param bytesWritten              每次下载多少
 *  @param totalBytesWritten         已经下载了多少
 *  @param totalBytesExpectedToWrite 文件的总长度
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    double progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
    self.currentProgress.text=[NSString stringWithFormat:@"%0.2f%%",progress*100];
    
    
    //    self.wlanLable.text=[NSString stringWithFormat:@"%lldKB/s",bytesWritten/102];
}



//当播放音乐时拔出耳机暂停
- (void)outputDeviceChanged:(NSNotification *)notification
{
    //NSLog(@"---%@", notification.userInfo);
    
    NSDictionary *dic = notification.userInfo;
    int changeReason = [dic[AVAudioSessionRouteChangeReasonKey] intValue];
    //等于AVAudioSessionRouteChangeReasonOldDeviceUnavailable表示旧输出不可用
    
    if (changeReason==AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
        
        AVAudioSessionRouteDescription *routeDescription = dic[AVAudioSessionRouteChangePreviousRouteKey];
        AVAudioSessionPortDescription *portDescription = [routeDescription.outputs firstObject];
        
        //原设备为耳机则暂停
        if ([portDescription.portType isEqualToString:@"Headphones"]) {
            [self startButtonAction];
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
